package net.lijingye.education.service.impl;

import net.lijingye.education.dao.*;
import net.lijingye.education.entity.*;
import net.lijingye.education.exception.*;
import net.lijingye.education.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.method.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LijingYe on 2016/3/31.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private TweetDao tweetDao;
    @Autowired
    private TweetReplyDao tweetReplyDao;
    @Autowired
    private FriendDao friendDao;
    @Autowired
    private FriendRequestDao friendRequestDao;

    public User getUserById(String userId) throws ObjectNotExistsException, DaoException {
        User user = userDao.getById(userId);
        if (null == user) {
            throw new ObjectNotExistsException("User `" + userId + "`");
        }
        return user;
    }

    public User getUserByAccessToken(String accessToken) throws ObjectNotExistsException, DaoException {
        Token token = tokenDao.getByAccessToken(accessToken);
        if (null == token) {
            throw new ObjectNotExistsException("Token `" + accessToken + "`");
        }
        User user = userDao.getById(token.getId());
        if (null == user) {
            throw new ObjectNotExistsException("User `" + token.getId() + "`");
        }
        return user;
    }

    public Tweet addTweet(Date time, String content, User user) throws DaoException {
        Tweet tweet = new Tweet(user.getId(), content, time, 0, new ArrayList<>(), new ArrayList<>());
        tweetDao.save(tweet);
        return tweet;
    }

    public Tweet addTweetFile(String tweetId, List<String> fileList) throws DaoException, ObjectNotExistsException {
        Tweet tweet = tweetDao.getById(tweetId);
        if (null == tweet) {
            throw new ObjectNotExistsException("Tweet `" + tweetId + "`");
        }
        List<TweetFile> tweetFileList = tweet.getTweetFileList();
        fileList.forEach(file -> {
            TweetFile tweetFile = new TweetFile(tweet.getId(), file);
            tweetFileList.add(tweetFile);
        });
        tweetDao.update(tweet);
        return tweet;
    }

    @Override
    public boolean isFriend(String userId1, String userId2) throws DaoException, ObjectNotExistsException {
        User user1 = userDao.getById(userId1);
        if (null == user1) {
            throw new ObjectNotExistsException("User `" + userId1 + "`");
        }
        User user2 = userDao.getById(userId2);
        if (null == user2) {
            throw new ObjectNotExistsException("User `" + userId2 + "`");
        }
        List<Friend> friendList = user1.getFriendList();
        for (Friend friend : friendList) {
            if (friend.getFriend().getId().equals(user2.getId())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void deleteFriend(String userId1, String userId2) throws DaoException, ObjectNotExistsException, FriendshipNotExistsException {
        User user1 = userDao.getById(userId1);
        if (null == user1) {
            throw new ObjectNotExistsException("User `" + userId1 + "`");
        }
        User user2 = userDao.getById(userId2);
        if (null == user2) {
            throw new ObjectNotExistsException("User `" + userId2 + "`");
        }
        List<Friend> friendShip = friendDao.findByQuery("WHERE (user.id='" + userId1 + "' AND friend.id='" + userId2 + "') OR (user.id='" + userId2 + "' AND friend.id='" + userId1 + "')");
        if (friendShip.size() <= 0) {
            throw new FriendshipNotExistsException("Friendship `" + userId1 + "`,`" + userId2 + "`");
        }
        for (Friend friend : friendShip) {
            friendDao.delete(friend);
        }
        List<FriendRequest> friendRequestList = friendRequestDao.findByQuery("WHERE (user.id='" + userId1 + "' AND target.id='" + userId2 + "') OR (user.id='" + userId2 + "' AND target.id='" + userId1 + "')");
        for (FriendRequest friendRequest : friendRequestList) {
            friendRequestDao.delete(friendRequest);
        }
    }

    @Override
    public void editFriendRequest(User user, String friendRequestId, boolean accept) throws DaoException, FriendRequestNotExistsException {
        Integer realFriendRequestId = Integer.valueOf(friendRequestId);
        FriendRequest friendRequest = friendRequestDao.getById(realFriendRequestId);
        if (null == friendRequest || 1 == friendRequest.getIsAnswered() || !user.getId().equals(friendRequest.getTarget().getId())) {
            throw new FriendRequestNotExistsException("FriendRequest `" + friendRequestId + "`");
        }
        friendRequest.setIsAnswered(1);
        if (accept) {
            friendRequest.setIsAccept(1);
            //传入的User即当前用户,而当前用户在friendRequest是作为target;
            User from = friendRequest.getUser();
            Friend friend1 = new Friend(user, from);
            friendDao.saveOrUpdate(friend1);
            Friend friend2 = new Friend(from, user);
            friendDao.saveOrUpdate(friend2);
        } else {
            friendRequest.setIsAccept(0);
        }
        friendRequestDao.update(friendRequest);
        List<FriendRequest> fromUserFriendRequestList = friendRequest.getUser().getFriendRequestList();
        for (FriendRequest fromUserFriendRequest : fromUserFriendRequestList) {
            if (fromUserFriendRequest.getUser().getId().equals(user.getId())) {
                fromUserFriendRequest.setIsAnswered(1);
                if (accept) {
                    fromUserFriendRequest.setIsAccept(1);
                } else {
                    fromUserFriendRequest.setIsAccept(0);
                }
                friendRequestDao.update(fromUserFriendRequest);
            }
        }
    }

    @Override
    public void addFriendRequest(User user, User target) throws DaoException, FriendRequestAlreadyExistsException {
        List<FriendRequest> friendRequestList = target.getFriendRequestList();
        for (FriendRequest friendRequest : friendRequestList) {
            if (friendRequest.getUser().getId().equals(user.getId())) {
                throw new FriendRequestAlreadyExistsException();
            }
        }
        FriendRequest friendRequest = new FriendRequest(0, 0, user, target);
        friendRequestDao.save(friendRequest);
    }

    @Override
    public void updateUserProfile(User user, String name, String gender, String birthday, String telephone, Province province, City city, String hobbies, String motto, String email) throws DaoException, ProfileProvinceNotExistsException, ProfileCityNotExistsException {
        if (null != name && !name.trim().equals("")) {
            user.setNickName(name);
        }
        try {
            int realGender = Integer.valueOf(gender);
            if (1 == realGender) {
                user.setGender(1);
            } else if (0 == realGender) {
                user.setGender(0);
            }
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date realBirthday = simpleDateFormat.parse(birthday);
            user.setBirthday(realBirthday);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        if (null != telephone && !telephone.trim().equals("")) {
            user.setTelephone(telephone);
        }
        if (null != motto && !motto.trim().equals("")) {
            user.setMotto(motto);
        }
        if (null != hobbies && !hobbies.trim().equals("")) {
            user.setHobbies(hobbies);
        }
        if (null != email && !email.trim().equals("")) {
            user.setEmail(email);
        }
        if (null != province) {
            user.setProvince(province);
        }
        if (null != city) {
            user.setCity(city);
        }
        userDao.update(user);
    }


}
